package com.sjh.lib_app.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.youth.banner.adapter.BannerAdapter
import com.sjh.lib_app.R

/**
 * 一个简单的banner适配器
 * @author ysj
 * @date 2020/8/19 11:06
 */
class SimpleBannerAdapter<T>(list: List<T>) : BannerAdapter<T, SimpleBannerAdapter.BannerViewHolder>(list) {

    private var if_onBind: OnBind<T, BannerViewHolder>? = null

    /**
     * ViewHolder
     * @author ysj
     * @date 2020/8/19 11:22
     */
    class BannerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var imageView: ImageView? = null

        init {
            imageView = itemView.findViewById(R.id.mImageView)
        }
    }
    fun clearAndSetData(list: List<T>){
        mDatas.clear()
        mDatas.addAll(list)
        notifyDataSetChanged()
    }
    override fun onCreateHolder(parent: ViewGroup?, viewType: Int): BannerViewHolder {
        val inflateItemView = inflateItemView(R.layout.app_banner_layout, parent)
        return if (inflateItemView == null) {
            BannerViewHolder(ImageView(parent?.context))
        } else BannerViewHolder(inflateItemView)
    }

    override fun onBindView(holder: BannerViewHolder?, data: T, position: Int, size: Int) {

        if_onBind?.onBind(holder!!, position, data)

    }


    /**
     * 解析布局
     */
    private fun inflateItemView(@LayoutRes layoutRes: Int, parent: ViewGroup?): View? {
        return LayoutInflater.from(parent?.context).inflate(layoutRes, parent, false)
    }


    private fun setOnBind(bind: OnBind<T, BannerViewHolder>) {
        if_onBind = bind
    }

    fun onBind(l: (holder: BannerViewHolder?, data: T, position: Int) -> Unit) {
        setOnBind(object : OnBind<T, BannerViewHolder> {
            override fun onBind(holder: BannerViewHolder, position: Int, data: T) {
                l(holder, data, position)
            }
        })
    }


    interface OnBind<in T, BannerViewHolder> {
        fun onBind(holder: BannerViewHolder, position: Int, data: T)
    }

}